package com.gqs.bookstore.web.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gqs.bookstore.dao.BookDao;
import com.gqs.bookstore.dao.CatalogDao;
import com.gqs.bookstore.dao.impl.BookDaoImpl;
import com.gqs.bookstore.dao.impl.CatalogDaoImpl;
import com.gqs.bookstore.util.Constants;
import com.gqs.bookstore.util.StringIsBlank;
import com.gqs.bookstore.vo.Book;
import com.gqs.bookstore.vo.Catalog;
import com.gqs.bookstore.vo.PageBean;

@WebServlet("/home.do")
public class HomeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private CatalogDao catalogDao  = new CatalogDaoImpl();
	private BookDao bookDao = new BookDaoImpl();
	
	//对于首页基本上都是url访问get请求
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		//这里从jsp的页面得到c_id,i,s[在前台页面已经写了，通过地址栏url方式传值]
		String cId = request.getParameter("cId");//分类id
		
		//当第一次点击侧边栏时，i和s一定为空，所以给其赋初值；然后当点击分页时，就用从页面传进去的值
		//StringUtil.isBlank(catalogId)为空才返回为true,然后给其赋初值1L,否则不为空返回false，那么就用传进来的值
		Long catalogId = StringIsBlank.isBlank(cId)?1L:Long.valueOf(cId);//索引
		//在整个项目中索引大小是在刚开始选择catalog时给定了,但是以后会改变的
		String i = request.getParameter("i");//索引
		Long pageIndex = StringIsBlank.isBlank(i)?1L:Long.valueOf(i);
		
		//在整个项目中页码大小是在刚开始选择catalog时给定了，以后都用这个给定的值
		String s = request.getParameter("s");//页大小
		Long pageSize = StringIsBlank.isBlank(s)?2L:Long.valueOf(s);
		
		List<Catalog> catalogList = null;
		PageBean<Book> pageBean = null;
		//这里必须要用try-catch:因为已经到了顶层，不能再往上抛了
		//补充：jsp页面就不用抓异常，因为内部把所有的异常都转化为运行时异常，即runtime异常
		try {
			catalogList =  catalogDao.findAll();//查到的是页面左边一栏所有的分类的信息列表
			pageBean = bookDao.findByPagination(catalogId, pageIndex, pageSize);//查到是右边页面中间的book信息
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		request.setAttribute("catalogId", catalogId);
		request.setAttribute("catalogList", catalogList);
		request.setAttribute("pageBean", pageBean);
		//request必须要用请求转发【地址栏不会变，后缀还是home.do】,而且还要在页面间传递数据，所以要用request 
		RequestDispatcher dispatcher = request.getRequestDispatcher(Constants.JSP_PATH + "index.jsp");
		dispatcher.forward(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
